package com.hdax.dm.interceptors;

import cn.hutool.json.JSONUtil;
import com.hdax.dm.common.utils.ResponseUtil;
import com.hdax.dm.constants.ResultEnumCode;
import com.hdax.dm.exceptions.TokenException;
import com.hdax.dm.utils.TokenUtil;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();
        String[] uriPaths = request.getRequestURI().split("/");
        if(uriPaths[1].equals("p")){
            //从请求头获取
            String token = request.getHeader("token");
            if(token == null){
                log.error("request header with not token!");
                outputStream.write(JSONUtil.toJsonStr(ResponseUtil.returnFail(ResultEnumCode.TOKEN_INVALID)).getBytes(StandardCharsets.UTF_8));
                return false;
            }
            Long userId = 0L;
            try{
                Map<String,String> result = TokenUtil.parseToken(token);
            }catch (Exception e){
                if(e instanceof ExpiredJwtException){
                    ExpiredJwtException exception = (ExpiredJwtException) e;
                    Map entries = redisTemplate.opsForHash().entries("token:" + Math.abs(userId));
                    if(entries == null || entries.size() == 0){
                        //登录状态已经失效
                        outputStream.write(JSONUtil.toJsonStr(ResponseUtil.returnFail(ResultEnumCode.REDIS_TOKEN_EXPIRE_ERROR)).getBytes(StandardCharsets.UTF_8));
                    }else{
                        outputStream.write(JSONUtil.toJsonStr(ResponseUtil.returnFail(ResultEnumCode.TOKEN_EXPIRE_ERROR)).getBytes(StandardCharsets.UTF_8));
                    }

                }else if(e instanceof TokenException){
                    TokenException exception = (TokenException) e;
                    outputStream.write(JSONUtil.toJsonStr(ResponseUtil.returnFail(exception)).getBytes(StandardCharsets.UTF_8));
                }
                return false;
            }
        }
        return true;
    }
}
